import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { tagModel } from './entities/tag.entity';

@Injectable()
export class TagService {
  async create(tagname: string) {
    const tag = await this.findOne(tagname);
    if (tag) {
      throw new HttpException(
        {
          message: '该标签已经存在',
        },
        HttpStatus.ACCEPTED,
      );
    }
    try {
      await tagModel.insertOne({ tagname, dynamics: [] });
    } catch (err) {
      throw new HttpException(
        {
          message: '服务器内部错误',
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  async findAll() {
    let tags = null;
    try {
      tags = await tagModel.findAll({});
    } catch (err) {}
    return tags;
  }

  async findOne(tagname: string) {
    let tag = null;
    try {
      tag = await tagModel.findOne({ tagname });
    } catch (err) {
      throw new HttpException(
        {
          message: '服务器内部错误',
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
    return tag;
  }
}
